package com.zyf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyf.client.HospitalFeignClient;
import com.zyf.client.PatientFeignClient;
import com.zyf.common.excption.YyghException;
import com.zyf.common.helper.HttpRequestHelper;
import com.zyf.common.result.ResultCodeEnum;
import com.zyf.constant.MqConst;
import com.zyf.enums.OrderStatusEnum;
import com.zyf.mapper.OrderInfoMapper;
import com.zyf.model.order.OrderInfo;
import com.zyf.model.user.Patient;
import com.zyf.service.OrderInfoService;
import com.zyf.service.RabbitService;
import com.zyf.service.WXPayService;
import com.zyf.vo.hosp.ScheduleOrderVo;
import com.zyf.vo.msm.MsmVo;
import com.zyf.vo.order.OrderCountQueryVo;
import com.zyf.vo.order.OrderMqVo;
import com.zyf.vo.order.OrderQueryVo;
import com.zyf.vo.order.SignInfoVo;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/** 订单操作，业务类实现类
 * @author zyf
 * @date 2021年05月31日 14:38
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private PatientFeignClient patientFeignClient;

    @Autowired
    private HospitalFeignClient hospitalFeignClient;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private WXPayService wxPayService;

    /**
     * 生成订单
     * @author zyf
     * @date 2021/5/31 14:48
     * @param scheduleId 排班id
     * @param patientId 就诊人id
     * @return java.lang.Long
     */
    @Override
    public Long submitOrder(String scheduleId, Long patientId) {
        //获取就诊人信息
        Patient patient = patientFeignClient.getPatientOrder(patientId);

        //获取排班信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);

        //判断当前时间是否可以预约
        if (new DateTime(scheduleOrderVo.getStartTime()).isAfterNow() || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()){
            throw new YyghException(ResultCodeEnum.TIME_NO);
        }

        //获取签名信息
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());

        OrderInfo orderInfo = new OrderInfo();
        //把scheduleOrderVo中的数据复制到orderInfo中
        BeanUtils.copyProperties(scheduleOrderVo,orderInfo);
        //向orderInfo添加其他数据
        String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo)
                .setScheduleId(scheduleId)
                .setUserId(patient.getUserId())
                .setPatientId(patientId)
                .setPatientName(patient.getName())
                .setPatientPhone(patient.getPhone())
                .setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        baseMapper.insert(orderInfo);

        //调用医院接口，实现预约挂号操作
        //设置调用医院接口需要的参数，参数放到Map中
        Map<String, Object> map = new HashMap<>();
        map.put("hoscode",orderInfo.getHoscode());
        map.put("depcode",orderInfo.getDepcode());
        map.put("hosScheduleId",orderInfo.getScheduleId());
        map.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        map.put("reserveTime",orderInfo.getReserveTime());
        map.put("amount",orderInfo.getAmount());

        map.put("name",patient.getName());
        map.put("certificatesType",patient.getCertificatesType());
        map.put("certificatesNo",patient.getCertificatesNo());
        map.put("sex",patient.getSex());
        map.put("birthdate",patient.getBirthdate());
        map.put("phone",patient.getPhone());
        map.put("isMarry",patient.getIsMarry());
        map.put("provinceCode",patient.getCityCode());
        map.put("cityCode",patient.getProvinceCode());
        map.put("districtCode",patient.getDistrictCode());
        map.put("address",patient.getAddress());

        //联系人
        map.put("contactsName",patient.getContactsName());
        map.put("contactsCertificatesType",patient.getContactsCertificatesType());
        map.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        map.put("contactsPhone",patient.getContactsPhone());
        map.put("timestamp", HttpRequestHelper.getTimestamp());

        String sign = HttpRequestHelper.getSign(map, signInfoVo.getSignKey());
        map.put("sign",sign);

        //请求医院系统接口
        JSONObject request = HttpRequestHelper.sendRequest(map, signInfoVo.getApiUrl() + "/order/submitOrder");
        if (request.getInteger("code")==200){
            //获取订单信息
            JSONObject data = request.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecodeId = data.getString("hosRecordId");
            //预约序号
            Integer number = data.getInteger("number");
            //取号时间
            String fetchTime = data.getString("fetchTime");
            //取号地址
            String fetchAddress = data.getString("fetchAddress");
            //更新订单
            orderInfo.setHosRecordId(hosRecodeId)
                    .setNumber(number)
                    .setFetchTime(fetchTime)
                    .setFetchAddress(fetchAddress);

            baseMapper.updateById(orderInfo);
            //排班可以预约数量
            Integer reservedNumber = data.getInteger("reservedNumber");
            //排班剩余预约数量
            Integer availableNumber = data.getInteger("availableNumber");

            //发送mq消息，号源更新和短信通知
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId)
                    .setReservedNumber(reservedNumber)
                    .setAvailableNumber(availableNumber);

            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("title",orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
            paramMap.put("amount",orderInfo.getAmount());
            paramMap.put("reserveDate",reserveDate);
            paramMap.put("name",orderInfo.getPatientName());
            paramMap.put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));

            msmVo.setParam(paramMap);
            orderMqVo.setMsmVo(msmVo);

            //设置消息发送
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);
        }else {
            throw new YyghException(request.getString("message"),ResultCodeEnum.FAIL.getCode());
        }

        return orderInfo.getId();
    }

    /**
     * 根据订单id查询订单的详细信息
     * @author zyf
     * @date 2021/6/2 14:21
     * @param orderId 订单id
     * @return com.zyf.model.order.OrderInfo
     */
    @Override
    public OrderInfo getOrder(String orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        return this.packOrderInfo(orderInfo);
    }



    /**
     * 获取订单列表
     * @author zyf
     * @date 2021/6/2 14:54
     * @param pageParam
     * @param queryVo
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.zyf.model.order.OrderInfo>
     */
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo queryVo) {
        //获取OrderQueryVo中的条件值
        String keyword = queryVo.getKeyword();//医院名称
        String orderStatus = queryVo.getOrderStatus();//订单状态
        Long patientId = queryVo.getPatientId();//就诊人名称
        String reserveDate = queryVo.getReserveDate();//安排时间
        String createTimeBegin = queryVo.getCreateTimeBegin();//开始时间
        String createTimeEnd = queryVo.getCreateTimeEnd();//结束时间
        String outTradeNo = queryVo.getOutTradeNo();//订单交易号
        String patientName = queryVo.getPatientName();//就诊人名称

        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(keyword)){
            wrapper.like("hosname",keyword);
        }
        if(!StringUtils.isEmpty(orderStatus)){
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(patientId)){
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(outTradeNo)){
            wrapper.eq("out_trade_no",outTradeNo);
        }
        if(!StringUtils.isEmpty(patientName)){
            wrapper.eq("patient_name",patientName);
        }
        if(!StringUtils.isEmpty(reserveDate)){
            wrapper.eq("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)){
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)){
            wrapper.le("create_time",createTimeEnd);
        }
        //调用方法进行分页条件查询
        IPage<OrderInfo> orderInfoPage = baseMapper.selectPage(pageParam, wrapper);
        orderInfoPage.getRecords().forEach(this::packOrderInfo);

        return orderInfoPage;
    }


    @Override
    public Map<String, Object> show(String orderId) {
        Map<String, Object> map = new HashMap<>();
        OrderInfo orderInfo = this.packOrderInfo(this.getById(orderId));
        map.put("orderInfo", orderInfo);
        Patient patient =  patientFeignClient.getPatientOrder(orderInfo.getPatientId());
        map.put("patient", patient);
        return map;
    }

    /**
     * 取消订单
     * @author zyf
     * @date 2021/6/4 10:41
     * @param orderId 订单id
     * @return java.lang.Boolean
     */
    @Override
    public Boolean cancelOrder(String orderId) {
        //获取订单信息
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        //查询是否在取消预约时间内
        DateTime dateTime = new DateTime(orderInfo.getQuitTime());
        if (dateTime.isBeforeNow()){
            throw new YyghException(ResultCodeEnum.CANCEL_ORDER_NO);
        }
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if (null == signInfoVo){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp",HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign",sign);

        JSONObject request = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl() + "/order/updateCancelStatus");
        if (request.getInteger("code")!=200){
            throw new YyghException(request.getString("message"),ResultCodeEnum.FAIL.getCode());
        }else {
            if(orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()){
                Boolean refund = wxPayService.refund(orderId);
                if (!refund){
                    throw new YyghException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                }
            }
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            baseMapper.updateById(orderInfo);

            //发送mq更新预约数量
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orderInfo.getScheduleId());

            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> paramMap = new HashMap<>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(paramMap);
            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);
            return true;
        }
    }

    /**
     * 监听消息 就诊通知
     * @author zyf
     * @date 2021/6/4 16:37
     */
    @Override
    public void patientTips() {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        wrapper.ne("order_status",OrderStatusEnum.CANCLE.getStatus());
        List<OrderInfo> orderInfoList = baseMapper.selectList(wrapper);
        orderInfoList.forEach(orderInfo -> {
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String,Object> param = new HashMap<>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);
        });
    }

    /**
     * 统计预约挂号数量
     * @author zyf
     * @date 2021/6/4 17:05
     * @return java.util.List<com.zyf.vo.order.OrderCountVo>
     */
    @Override
    public Map<String,Object> selectOrderCount(OrderCountQueryVo vo) {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.select("reserve_date AS reserveDate","COUNT(*) AS count");
        if (!StringUtils.isEmpty(vo.getHosname())){
            wrapper.like("hosname",vo.getHosname());
        }
        if (!StringUtils.isEmpty(vo.getReserveDateBegin())){
            wrapper.ge("reserve_date",vo.getReserveDateBegin());
        }else {
            wrapper.ge("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        }
        if (!StringUtils.isEmpty(vo.getReserveDateEnd())){
            wrapper.le("reserve_date",vo.getReserveDateEnd());
        }
        wrapper.groupBy("reserve_date");
        wrapper.orderBy(true,true,"reserve_date");
        List<OrderInfo> orderInfoList = baseMapper.selectList(wrapper);

        List<Date> reserveDateList = orderInfoList.stream().map(OrderInfo::getReserveDate).collect(Collectors.toList());
        List<String> reserveDateStringList = new ArrayList<>();
        reserveDateList.forEach(date -> {
            String s = new DateTime(date).toString("yyyy-MM-dd");
            reserveDateStringList.add(s);
        });

        List<Integer> countList = orderInfoList.stream().map(OrderInfo::getCount).collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("dateList",reserveDateStringList);
        map.put("countList",countList);
        return map;
    }

    private OrderInfo packOrderInfo(OrderInfo orderInfo){
        orderInfo.getParam().put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }
}
